package com.soup.common.module.sys.api;

import com.soup.common.constant.CommonConstant;
import com.soup.common.entity.QueryParam;
import com.soup.common.entity.Result;
import com.soup.common.module.sys.data.MenuRequest;
import com.soup.common.module.sys.entity.Menu;
import com.soup.common.module.sys.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 菜单api
 *
 * @author zhaoyi
 */
@RestController
@RequestMapping("/menu")
public class MenuApi {

    @Autowired
    private MenuService menuService;

    /**
     * 查询所有菜单，分级查询
     */
    @GetMapping
    public Result list(String searchKeywords) {
        return new Result().success(menuService.allMenus(searchKeywords));
    }

    /**
     * 查询所有菜单，可以指定菜单层级进行查询
     */
    @GetMapping("/all")
    public List<Menu> all(@RequestParam(required = false) Integer level) {
        QueryParam queryParam = new QueryParam(Menu.class);
        QueryParam.Criteria criteria = queryParam.createCriteria();
        if (null != level) {
            criteria.andLike("menuLevel", level.toString());
        }
        // 过滤功能菜单，方法菜单不可再挂下级
        criteria.andNotEqualTo("menuType", CommonConstant.METHOD_MENU);

        // 执行查询
        return menuService.selectByQueryParam(queryParam);
    }

    /**
     * 新增菜单
     */
    @PostMapping
    public int add(@RequestBody @Valid MenuRequest menuRequest) {
        return menuService.add(menuRequest);
    }

    /**
     * 修改菜单
     */
    @PutMapping("/{menuId}")
    public int update(@PathVariable Integer menuId, @RequestBody @Valid MenuRequest menuRequest) {
        return menuService.update(menuId, menuRequest);
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{menuId}")
    public int del(@PathVariable Integer menuId) {
        return menuService.del(menuId);
    }
}
